from PySide6.QtWidgets import QMainWindow, QApplication, QMessageBox, QWidget
from ManagePdf import Ui_MainWindow as mainWindow
from fig2pdf import Ui_MainWindow as fig2pdfWindow
from mergePdf import Ui_MainWindow as mergePdfWindow
from word2pdf import Ui_MainWindow as word2pdfWindow
from pdf2word import Ui_MainWindow as pdf2wordWindow
from splitPdf import Ui_MainWindow as splitPdfWindow
from getFigFromPdf import Ui_MainWindow as getFigOfPdfWindow
from setPassForPdf import Ui_MainWindow as setPassForPdfWindow
from clearPassOfPdf import Ui_MainWindow as clearPassOfPdfWindow

from PdfFunctions.ConvertToPdf import MergeFigToPdf, MergePdf, SplitPdf, FileToPdf
from PdfFunctions.ConvertPdf import PdfToFile, extractImages
from PdfFunctions.ConvertPwOfPdf import PlusPwOnPdf, ClearPwOnPdf
from FileSelector import FileSelector

import sys
import os


# 事件执行完成结果的消息对话框，用于装饰到每个事件执行函数
def event_finish(func):
    def do_event(self):
        try:
            func(self)
            QMessageBox.about(QWidget(), "消息对话框", "执行完成！")
        except Exception as e:
            QMessageBox.about(QWidget(), "消息对话框", f"error!:\n{e}")
    return do_event


class Main(QMainWindow, mainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)


class Child_fig2pdf(QMainWindow, fig2pdfWindow):
    def __init__(self):
        super(Child_fig2pdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFolder.clicked.connect(lambda: FileSelector(self.FigPath).select_folder())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.fig2pdfButton.clicked.connect(self.get_result)
        
    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourcePath = self.FigPath.text()
        sourceFileNames = os.listdir(self.FigPath.text())
        sourceFiles = [os.path.join(sourcePath, f_name) for f_name in sourceFileNames]
        targetFile = os.path.join(sourcePath, self.ResultFile.text())
        MergeFigToPdf(sourceFiles, targetFile)


class Child_mergePdf(QMainWindow, mergePdfWindow):
    def __init__(self):
        super(Child_mergePdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFolder.clicked.connect(lambda: FileSelector(self.PdfPath).select_folder())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.merge_pdfButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourcePath = self.PdfPath.text()
        sourceFileNames = os.listdir(self.PdfPath.text())
        sourceFiles = [os.path.join(sourcePath, f_name) for f_name in sourceFileNames]
        targetFile = os.path.join(sourcePath, self.ResultFile.text())
        MergePdf(sourceFiles, targetFile)


class Child_word2pdf(QMainWindow, word2pdfWindow):
    def __init__(self):
        super(Child_word2pdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFile.clicked.connect(lambda: FileSelector(self.WordFile).select_file())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.word2pdfButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.WordFile.text()
        FileToPdf(sourceFile)


class Child_pdf2word(QMainWindow, pdf2wordWindow):
    def __init__(self):
        super(Child_pdf2word, self).__init__()
        self.setupUi(self)

        self.btnSelectFile.clicked.connect(lambda: FileSelector(self.PdfFile).select_file())
        self.pdf2wordButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.PdfFile.text()
        if self.docRadioButton.isChecked():
            targetType = 'docx'
        elif self.pptRadioButton.isChecked():
            targetType = 'pptx'
        else:
            targetType = 'docx'
        PdfToFile(sourceFile, targetType)


class Child_splitPdf(QMainWindow, splitPdfWindow):
    def __init__(self):
        super(Child_splitPdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFile.clicked.connect(lambda: FileSelector(self.PdfFile).select_file())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.splitButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.PdfFile.text()
        sourcePath = os.path.dirname(sourceFile)

        targetFile = os.path.join(sourcePath, self.ResultFile.text())

        buf_pages = self.pageNums.text().split(' ')
        page_nums = []
        for page in buf_pages:
            if '-' in page:
                buf = [int(x) for x in page.split('-')]
                page_nums = page_nums + list(range(buf[0], buf[1] + 1))
            else:
                page_nums.append(int(page))
        SplitPdf(sourceFile, targetFile, page_nums)


class Child_getFigOfPdf(QMainWindow, getFigOfPdfWindow):
    def __init__(self):
        super(Child_getFigOfPdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFile.clicked.connect(lambda: FileSelector(self.PdfFile).select_file())
        self.getFigButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.PdfFile.text()
        sourcePath = os.path.dirname(sourceFile)

        targetPath = os.path.join(sourcePath, 'tempFigs')
        os.makedirs(targetPath, exist_ok=False)

        extractImages(sourceFile, targetPath)


class Child_setPassForPdf(QMainWindow, setPassForPdfWindow):
    def __init__(self):
        super(Child_setPassForPdf, self).__init__()
        self.setupUi(self)

        self.btnSelectFile.clicked.connect(lambda: FileSelector(self.PdfFile).select_file())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.setPassButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.PdfFile.text()
        sourcePath = os.path.dirname(sourceFile)
        targetFile = os.path.join(sourcePath, self.ResultFile.text() + '.pdf')
        file_pass = self.setPassEdit.text()
        PlusPwOnPdf(sourceFile, targetFile, pw=file_pass)
        # QMessageBox.about(QWidget(), "消息对话框", "执行完成！")


class Child_clearPassOfPdf(QMainWindow, clearPassOfPdfWindow):
    def __init__(self):
        super(Child_clearPassOfPdf, self).__init__()
        self.setupUi(self)

        self.btnSelecFile.clicked.connect(lambda: FileSelector(self.PdfFile).select_file())
        self.btnSelectTargetFile.clicked.connect(lambda: FileSelector(self.ResultFile).save_file())
        self.clearPassButton.clicked.connect(self.get_result)

    def open(self):
        self.show()

    @event_finish
    def get_result(self):
        sourceFile = self.PdfFile.text()
        sourcePath = os.path.dirname(sourceFile)
        targetFile = os.path.join(sourcePath, self.ResultFile.text())
        file_pass = self.passEdit.text()
        ClearPwOnPdf(sourceFile, targetFile, pw=file_pass)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    main = Main()
    fileSelector = FileSelector()
    childFig2pdf = Child_fig2pdf()
    childMergePdf = Child_mergePdf()
    childWord2pdf = Child_word2pdf()
    chilePdf2word = Child_pdf2word()
    childSplitPdf = Child_splitPdf()
    childGetFigOfPdf = Child_getFigOfPdf()
    chiledSetPassForPdf = Child_setPassForPdf()
    chiledClearPassOfPdf = Child_clearPassOfPdf()

    main.show()
    main.fig2pdfButton.clicked.connect(childFig2pdf.open)
    main.mergePdfButton.clicked.connect(childMergePdf.open)
    main.word2pdfButton.clicked.connect(childWord2pdf.open)
    main.pdf2wordButton.clicked.connect(chilePdf2word.open)
    main.splitPdfButton.clicked.connect(childSplitPdf.open)
    main.getFigFromPdfButton.clicked.connect(childGetFigOfPdf.open)
    main.setPassForPdfButton.clicked.connect(chiledSetPassForPdf.open)
    main.purgePassFromPdfButton.clicked.connect(chiledClearPassOfPdf.open)

    sys.exit(app.exec())
